package cn.lzm.system.service.impl;

import cn.lzm.org.domain.Department;
import cn.lzm.system.domain.Menu;
import cn.lzm.system.mapper.MenuMapper;
import cn.lzm.system.service.IMenuService;
import cn.lzm.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lzm
 * @since 2022-10-24
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> queryAll() {
        ArrayList<Menu> menuList = new ArrayList<>();
        for (Menu menu : menuMapper.findAll()) {
            if (menu.getParentId() == null) {
                menuList.add(menu);
            }
        }
        return menuList;
    }

    @Override
    public List<Menu> tree() {
//        // 获取所有角色
        List<Menu> menus = menuMapper.tree();
        List menusRusult = new ArrayList<>();
        for (Menu menu : menus) {
            if (menu.getParentId()==null){
                menusRusult.add(menu);
                List<Menu> children = new ArrayList<>();
                for (Menu menuSon : menus) {
                    if (menuSon.getParentId()!=null && menuSon.getParentId() == menu.getId()){
                        children = menu.getChildren();
                        children.add(menuSon);
                    }
                }
            }

            }

        return menusRusult;
//        ArrayList<Menu> result = new ArrayList<>();
//        List<Menu> menus = menuMapper.tree();
//        Map<Long, Menu> map = menus.stream().collect(Collectors.toMap(Menu::getId, e -> e));
//        menus.forEach(menu->{
//            if (null == menu.getParentId()) {
//                result.add(menu);
//            } else {
//                Menu parent = map.get(menu.getParentId());
//                if (null == parent) {
//                    return;
//                }
//                parent.getChildren().add(menu);
//            }
//        });
//        return result;
    }

}
